package com.neuedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.upload.FastImageFile;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.neuedu.pojo.Project;
import com.neuedu.mapper.ProjectMapper;
import com.neuedu.service.IProjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;

/**
 * <p>
 * 项目 服务实现类
 * </p>
 *
 * @author liuyong
 * @since 2020-09-17
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {
    @Resource
    FastFileStorageClient fastFileStorageClient;
    @Override
    public  Object list(Project project) {
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(project.getName())){
            wrapper.like("name",project.getName());
        }
        if(project.getActive() != null){
            wrapper.eq("active",project.getActive());
        }
        if(project.getWithPage() == 1) {
            return page(new Page<>(project.getPageNo(), project.getPageSize()), wrapper);
        }else {
            return  this.list(wrapper);
        }
    }

    @Override
    public boolean add(Project project) throws IOException {
        MultipartFile file=project.getMultipartFile();
        FastImageFile fastImageFile=new FastImageFile(
                file.getInputStream(),
                file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()),
                new HashSet<>()
        );
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        wrapper.eq("name",project.getName());
        Project query = this.getOne(wrapper);
        if(query == null )
        {
            StorePath storePath=fastFileStorageClient.uploadImage(fastImageFile);
            LocalDateTime dateTime=LocalDateTime.now();
            project.setActive(1);
            project.setCreateTime(dateTime);
            project.setUpdateTime(dateTime);
            project.setApplyFileUrl(storePath.getFullPath());
            return  this.save(project);

        }
        else {return false;}

    }
}
